import dataModel from '@/models/panel-config-data.js';
import { EMIT_PARAMS_OBJ } from '@/utils/constant';
import { isEmptyObject } from '@/utils/util';

export default {
  data() {
    return {
      isBlank: true, // 点击处是否空白
      lastParams: null, // 上一次发出的参数，重新请求数据会清空
    };
  },
  methods: {
    isSameParams(item, index) {
      let flag = false;
      if (!isEmptyObject(this.lastParams)) {
        if (
          String(index) === String(this.lastParams.index) &&
          String(item.name) === String(this.lastParams.name ) &&
          String(item.value) === String(this.lastParams.value)
        ) {
          flag = true;
        }
      }
      return flag;
    },
    sendAllMessages(item, index, mappingObj) {
      this.executeAction('', item);
      if (this.orgConfig.events[0].type !== 'out') {
        return;
      }
      this.isBlank = false;
      if (this.isSameParams(item, index)) {
        this.lastParams = null;
        this.sendEmptyMessages();
        return;
      }
      this.lastParams = item;
      this.lastParams.index = index;
      const evtKey = this.orgConfig.events[0].key || 'item-click';
      const outObj = {};
      const { key } = this.orgConfig.events[0].parameters[0];
      const { paramKey } = this.config.events[0]; // 字段名code
      const { tableData } = this.config.config.data;
      const col = tableData.find(t => String(t.mapping) === String(paramKey));
      if (!col) {
        return;
      }

      if (mappingObj) {
        outObj[key] = item[mappingObj[col.field]];
      } else {
        col.field === 's' ? (outObj[key] = item.series) : (outObj[key] = item.value);
      }

      const keys = [this.config.events[0].parameters[0].key];
      const parameters = {
        [keys[0]]: outObj[key],
      };

      outObj[EMIT_PARAMS_OBJ] = {
        eventKey: this.config.events[0].key,
        type: 'terms',
        keys,
        parameters,
        widgetInstanceId: this.widgetInstanceId,
        sendTime: new Date().getTime(),
      };
      this.vsEmit(evtKey, outObj);
    },
    sendEmptyMessages() {
      if (this.orgConfig.events[0].type !== 'out') {
        return;
      }
      this.lastParams = null;
      const evtKey = this.orgConfig.events[0].key || 'item-click';
      const { key } = this.orgConfig.events[0].parameters[0];

      // 将key和参数放在每一条事件里面，防止多事件混用key
      const sKey = this.config.events[0].parameters[0].key; // 对应 "事件（key）"
      const parameters = { [sKey]: '' };

      const outObj = {};
      outObj[key] = '';
      outObj[EMIT_PARAMS_OBJ] = {
        eventKey: this.config.events[0].key,
        key: this.config.events[0].parameters[0].key,
        type: 'terms',
        widgetInstanceId: this.widgetInstanceId,
        keys: [sKey],
        parameters,
        sendTime: new Date().getTime(), // 事件发送时间，用于接收事件排序，一个组件接收多个事件时，如果没法多个同时使用，取最新一个，比如通用地图图层显示隐藏
      };
      this.vsEmit(evtKey, outObj);
    },

    // api请求获取图表数据
    getChartData() {
      const { data } = this.config.config;

      // 如果dataSourceType为静态数据,把数据放到Vuex，发出事件，然后退出
      if (data.dataSourceType === 'staticData') {
        const result = this.getStaticData();
        this.sendDataToConfig(result);
        this.isNoData = !result.length;
        if (!this.isNoData) {
          this.handleMultiValueResult(result, this.isIcon);
        }

        // 重置数据异常状态， 若未设置异常状态的组件不影响
        this.resetAbnormalType();
        return;
      }

      // api请求，拿到数据
      this.isLoading = true;
      this.isNoData = false;
      this.autoRefresh();
      const method = `getChartData${data.dataSourceType}`;
      const params = this.getCorrectParams(this.params, data.dataSourceType);
      dataModel[method](params, data)
        .then(_result => {
          const result = window.CustomerDiy?.formatApiData?.(_result, this) || _result;

          this.isNoData = !result.length;

          // 重置数据异常状态
          if (result === _result) {
            this.resetAbnormalType();
            this.reportIfFieldsError(params?.propertyMapping, result);
          }
          if (this.autoRefreshIsSameRes(result)) {
            return;
          }
          this.lastParams = null;
          this.sendDataToConfig(result);
          if (!this.isNoData) {
            this.handleMultiValueResult(result, this.isIcon);
          }
        })
        .catch(err => {
          this.handleChartDataError(err);
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    handleRealTimeCommunication(realTimeData) {
      if (this.config.config.property.isDebounce && this.isStopRealData) {
        return;
      }
      const result = this.getResult(realTimeData);
      if (this.isNoData || this.autoRefreshIsSameRes(result)) {
        this.isLoading = false;
        return;
      }
      this.handleMultiValueResult(result, this.isIcon);
      this.isLoading = false;
    },
  },
  mounted() {
    // 点击空白处传空值
    let oDiv = document.querySelector(`#chartMain${this.chartId}`);
    if (oDiv) {
      oDiv.onclick = () => {
        // 数值类取消选中状态
        if (this.selectedIndex || this.selectedIndex === 0) {
          this.selectedIndex = -1;
        }

        // 单数值取消选中状态
        if (this.isSelected) {
          this.isSelected = false;
        }

        if (this.isBlank) {
          this.sendEmptyMessages();
        }
        this.isBlank = true;
      };
      oDiv = null;
    }
  },
};
